package com.deepinblog.hot.controller;

import com.deepinblog.hot.cache.GuavaService;
import com.deepinblog.hot.cache.RedisService;
import com.deepinblog.hot.po.TJob;
import com.google.common.cache.LoadingCache;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

@RestController
@RequestMapping(value = "/hot/position")
public class HotPositionController implements InitializingBean {

    @Autowired
    private RedisService redisService;


    @Autowired
    private GuavaService guavaService;

    LoadingCache<String, Object> cache = null;


    /**
     * 初始化到Guava Cache
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        init();
    }

    @RequestMapping(value = "getFromRedis")
    public List<TJob> getHotPositionsFromRedis() throws Exception {
        return redisService.getHotList();
    }


    @RequestMapping(value = "init")
    public String init() throws ExecutionException {
        cache = guavaService.init();
        cache.get("HOTLIST");
        return "SUC";
    }


    @RequestMapping(value = "getFromGuava")
    public List<TJob> getHotPositionsFromGuava() throws Exception {


        //返回的数据
        List<TJob> dlist = new ArrayList<>();

        //读取列表
        Object glist = guavaService.get("HOTLIST", cache);
        //    Object glist = cache.getIfPresent("HOTLIST");
        //本地缓存有
        if (glist != null && ((List) glist).size() != 0) {
            for (Object o : (List) glist) {
                dlist.add((TJob) o);
            }

        }

        return dlist;

    }

}
